#! /usr/bin/env python
#coding=utf-8
import  sys,urllib2,json,time,httplib
import MySQLdb
import multiprocessing
reload(sys)
sys.setdefaultencoding( "utf-8" )
httplib.HTTPConnection._http_vsn = 10
httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'

#正式连接-----------
#host = "drdsrtok600s5n74.drds.aliyuncs.com"
#user = "hefantv"
#passwd = "HEfantv3_9a5"
#db = "hefantv"
#测试连接--------------
host = "drdsjsq4v76a23pa.drds.aliyuncs.com"
user = "hefantest"
passwd = "HEfantv3_9a5"
db = "hefantest"
#开发连接--------------
#host = "drdshmif9192k8au.drds.aliyuncs.com"
#user = "hefandev"
#passwd = "devhfDEV8v97"
#db = "hefandev"
port = 3306
charset='utf8'

lock = multiprocessing.Lock()

#
# 获取需要处理记录条数
#
def queryCount() :
    connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
    cursor = connect.cursor()
    sql = "SELECT COUNT(1) FROM web_user WHERE is_del=0 AND IFNULL(im_token_ry,'')='' "
    cursor.execute(sql)
    data = cursor.fetchone()
    cursor.close()
    connect.close()
    return data[0]

#
# 分批次获取操作的记录
#
def queryInfoPage(pageNum) :
    beginNum = (pageNum-1)*bachNum
    connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
    cursor = connect.cursor()
    sql = "select user_id,nick_name,head_img FROM web_user WHERE is_del=0 AND IFNULL(im_token_ry,'')='' order by id limit %d,%d"%(beginNum,bachNum)
    cursor.execute(sql)
    data = cursor.fetchall()
    cursor.close()
    connect.close()
    return data

#
# 获取融云im的token
#
def getRyTokenReq(userId,nickName,headImg) :
    #nickName = nickName if nickName else userId
    #headImg = headImg if headImg else defalutHeadImg
    reqUrl = "%s?userId=%s&name=%s&portraitUri=%s" % (url, userId, userId,defalutHeadImg)
    #print reqUrl
    req = urllib2.Request(reqUrl)
    res_data = urllib2.urlopen(req)
    resData = json.loads(res_data.read())
    print resData
    time.sleep(0.005)
    if resData["code"] == 1000 and resData["data"] :
        return resData["data"]
    else:
        return ""

def saveInfoInTemp(strArray) :
    if len(strArray) > 0:
        connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
        cursor = connect.cursor()
        sql = "insert into web_user_his_ry_temp(user_id,im_token_ry) values " + ",".join(strArray)
        cursor.execute(sql)
        connect.commit()
        cursor.close()
        connect.close()

#
# 操作执行方法
#
def opreateMehtod(pageNum) :
    infos = queryInfoPage(pageNum)
    strArray = []
    for info in infos :
        token = getRyTokenReq(info[0],info[1],info[2])
        if token :
            strArray.append("('%s','%s')" % (info[0], token))
        if len(strArray) >= bachInsertNum :
            saveInfoInTemp(strArray)
            strArray = []
    if len(strArray) > 0 :
        saveInfoInTemp(strArray)

#
# 将临时表中的ry token更新到用户表中
#
def updateRyToken() :
    connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
    cursor = connect.cursor()
    sql = """UPDATE web_user a SET im_token_ry=(SELECT im_token_ry FROM web_user_his_ry_temp WHERE user_id=a.user_id)
            WHERE EXISTS(SELECT 1 FROM web_user_his_ry_temp WHERE user_id=a.user_id)"""
    cursor.execute(sql)
    connect.commit()
    cursor.close()
    connect.close()



#url = "http://10.26.241.75:8055/services/rongIm/getToken"
#url = "http://10.44.205.218:8055/services/rongIm/getToken"
url = "http://127.0.0.1:8055/services/rongIm/getToken"
defalutHeadImg = "http://img.hefantv.com/default_head.png"
bachInsertNum = 500;
bachNum = 10000
if __name__ =='__main__' :
    beginTime = time.clock()
    countNum = queryCount()
    step = countNum/bachNum + (1 if countNum%bachNum > 0 else 0)
    print "---"+str(countNum)+"---"+str(step)+"---"
    mgr = multiprocessing.Manager()
    threads = []
    for i in xrange(1,step+1):
        t_thread = multiprocessing.Process(target=opreateMehtod, args=(i,))
        print "-----t_thread start [%d]----" % (i)
        t_thread.start();
        threads.append(t_thread)

    for t_thread in threads:
        t_thread.join()
        print "-----t_thread end ----"

    print "-----update ry token to web_user begin ---"
    updateRyToken();
    print "-----update ry token to web_user end ---"
    print "web_user ry im token init end time:%d s" % (time.clock() - beginTime)
